package com.pig4cloud.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.dto.UserLoginDTO;
import com.pig4cloud.entity.UserEntity;
import com.pig4cloud.mapper.UserMapper;
import com.pig4cloud.service.UserService;
import com.pig4cloud.util.JwtUtil;
import com.pig4cloud.vo.UserLoginVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

	private final WxMaService wxMaService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserLoginVO wxLoginUser(UserLoginDTO userLoginDTO) throws WxErrorException {
		WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(userLoginDTO.getCode());
		log.info("微信code解析结果:{}", session);
		UserLoginVO result = new UserLoginVO();
		UserEntity user = this.getOne(Wrappers.<UserEntity>lambdaQuery()
				.eq(UserEntity::getOpenid, session.getOpenid()));
		result.setSessionKey(session.getSessionKey());
		if (BeanUtil.isNotEmpty(user)) {
			result.setToken(JwtUtil.createToken(user));
			//不为空则为老用户,直接获取token返回即可
			result.setUserInfo(user);
			return result;
		}
		//新用户注册流程
		UserEntity registerUser = new UserEntity();
		registerUser.setOpenid(session.getOpenid());
		registerUser.setTenantId(0L);
		registerUser.setUsername("用户" + RandomUtil.randomNumbers(6));
		registerUser.setAvatarUrl("https://new-saas-1303948738.cos.ap-guangzhou.myqcloud.com/farm/avator.png");
		this.save(registerUser);
		result.setToken(JwtUtil.createToken(registerUser));
		result.setUserInfo(registerUser);
		return result;
	}
}
